/**
 * 音频可视化器标准接口
 * 所有可视化器都必须实现这个接口
 */
class VisualizerInterface {
    constructor(canvas, ctx) {
        this.canvas = canvas;
        this.ctx = ctx;
        this.isInitialized = false;
        this.animationId = null;
        this.settings = {};
    }

    /**
     * 初始化可视化器
     * @param {Object} config - 配置参数
     */
    init(config = {}) {
        this.settings = { ...this.getDefaultSettings(), ...config };
        this.isInitialized = true;
        return this;
    }

    /**
     * 获取默认设置
     * @returns {Object} 默认配置
     */
    getDefaultSettings() {
        return {
            backgroundColor: 'rgba(0, 0, 0, 0.1)',
            primaryColor: '#667eea',
            secondaryColor: '#764ba2',
            sensitivity: 1.0,
            smoothing: 0.8
        };
    }

    /**
     * 获取可视化器信息
     * @returns {Object} 可视化器元数据
     */
    getInfo() {
        return {
            name: 'Base Visualizer',
            description: '基础可视化器',
            author: 'AudioNN',
            version: '1.0.0',
            category: 'basic'
        };
    }

    /**
     * 渲染一帧
     * @param {Uint8Array} frequencyData - 频谱数据
     * @param {Uint8Array} cachedData - 缓存的频谱数据（可选）
     * @param {number} currentTime - 当前播放时间
     */
    render(frequencyData, cachedData = null, currentTime = 0) {
        throw new Error('render() method must be implemented');
    }

    /**
     * 更新设置
     * @param {Object} newSettings - 新的设置
     */
    updateSettings(newSettings) {
        this.settings = { ...this.settings, ...newSettings };
    }

    /**
     * 获取当前设置
     * @returns {Object} 当前设置
     */
    getSettings() {
        return { ...this.settings };
    }

    /**
     * 调整画布大小
     * @param {number} width - 新宽度
     * @param {number} height - 新高度
     */
    resize(width, height) {
        // 子类可以重写此方法
    }

    /**
     * 清理资源
     */
    cleanup() {
        if (this.animationId) {
            cancelAnimationFrame(this.animationId);
            this.animationId = null;
        }
        this.isInitialized = false;
    }

    /**
     * 获取可配置的参数
     * @returns {Array} 参数配置列表
     */
    getConfigurableParams() {
        return [
            {
                key: 'sensitivity',
                label: '灵敏度',
                type: 'range',
                min: 0.1,
                max: 2.0,
                step: 0.1,
                default: 1.0
            },
            {
                key: 'primaryColor',
                label: '主色调',
                type: 'color',
                default: '#667eea'
            },
            {
                key: 'secondaryColor',
                label: '副色调',
                type: 'color',
                default: '#764ba2'
            }
        ];
    }

    // 辅助方法
    clearCanvas() {
        const width = this.canvas.width / window.devicePixelRatio;
        const height = this.canvas.height / window.devicePixelRatio;
        this.ctx.fillStyle = this.settings.backgroundColor;
        this.ctx.fillRect(0, 0, width, height);
    }

    createGradient(x1, y1, x2, y2, colors) {
        const gradient = this.ctx.createLinearGradient(x1, y1, x2, y2);
        colors.forEach((color, index) => {
            gradient.addColorStop(index / (colors.length - 1), color);
        });
        return gradient;
    }

    hslToRgb(h, s, l) {
        h /= 360;
        s /= 100;
        l /= 100;
        const a = s * Math.min(l, 1 - l);
        const f = n => {
            const k = (n + h / (1/12)) % 12;
            return l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
        };
        return [Math.round(255 * f(0)), Math.round(255 * f(8)), Math.round(255 * f(4))];
    }
}

/**
 * 可视化器管理器
 */
class VisualizerManager {
    constructor() {
        this.visualizers = new Map();
        this.currentVisualizer = null;
        this.canvas = null;
        this.ctx = null;
    }

    /**
     * 设置画布
     * @param {HTMLCanvasElement} canvas - 画布元素
     */
    setCanvas(canvas) {
        this.canvas = canvas;
        this.ctx = canvas.getContext('2d');
    }

    /**
     * 注册可视化器
     * @param {string} id - 可视化器ID
     * @param {class} VisualizerClass - 可视化器类
     */
    register(id, VisualizerClass) {
        this.visualizers.set(id, VisualizerClass);
    }

    /**
     * 批量注册可视化器
     */
    registerFromGlobal() {
        if (window.visualizerRegistrations) {
            window.visualizerRegistrations.forEach(registration => {
                this.register(registration.id, registration.class);
                console.log(`Registered visualizer: ${registration.id}`);
            });
        }
    }

    /**
     * 获取所有已注册的可视化器信息
     * @returns {Array} 可视化器信息列表
     */
    getAvailableVisualizers() {
        const visualizers = [];
        for (const [id, VisualizerClass] of this.visualizers) {
            const instance = new VisualizerClass(this.canvas, this.ctx);
            visualizers.push({
                id,
                ...instance.getInfo()
            });
        }
        return visualizers;
    }

    /**
     * 切换到指定的可视化器
     * @param {string} id - 可视化器ID
     * @param {Object} config - 配置参数
     * @returns {boolean} 是否切换成功
     */
    switchTo(id, config = {}) {
        if (!this.visualizers.has(id)) {
            console.error(`Visualizer ${id} not found`);
            return false;
        }

        // 清理当前可视化器
        if (this.currentVisualizer) {
            this.currentVisualizer.cleanup();
        }

        // 创建新的可视化器实例
        const VisualizerClass = this.visualizers.get(id);
        this.currentVisualizer = new VisualizerClass(this.canvas, this.ctx);
        this.currentVisualizer.init(config);

        return true;
    }

    /**
     * 渲染当前可视化器
     * @param {Uint8Array} frequencyData - 频谱数据
     * @param {Uint8Array} cachedData - 缓存数据
     * @param {number} currentTime - 当前时间
     */
    render(frequencyData, cachedData = null, currentTime = 0) {
        if (this.currentVisualizer && this.currentVisualizer.isInitialized) {
            this.currentVisualizer.render(frequencyData, cachedData, currentTime);
        }
    }

    /**
     * 更新当前可视化器设置
     * @param {Object} settings - 新设置
     */
    updateSettings(settings) {
        if (this.currentVisualizer) {
            this.currentVisualizer.updateSettings(settings);
        }
    }

    /**
     * 获取当前可视化器的配置参数
     * @returns {Array} 配置参数列表
     */
    getCurrentVisualizerParams() {
        if (this.currentVisualizer) {
            return this.currentVisualizer.getConfigurableParams();
        }
        return [];
    }

    /**
     * 获取当前可视化器设置
     * @returns {Object} 当前设置
     */
    getCurrentSettings() {
        if (this.currentVisualizer) {
            return this.currentVisualizer.getSettings();
        }
        return {};
    }

    /**
     * 调整画布大小
     * @param {number} width - 新宽度
     * @param {number} height - 新高度
     */
    resize(width, height) {
        if (this.currentVisualizer) {
            this.currentVisualizer.resize(width, height);
        }
    }

    /**
     * 清理所有资源
     */
    cleanup() {
        if (this.currentVisualizer) {
            this.currentVisualizer.cleanup();
        }
        this.visualizers.clear();
        this.currentVisualizer = null;
    }
}

// 导出到全局
window.VisualizerInterface = VisualizerInterface;
window.VisualizerManager = VisualizerManager;
